// pages/member/distribution/distribution.js
const skinBehavior = require("../../../utils/themeSkin/skinBehavior");
const echarts = require("../../../ec-canvas/echarts"); //路径一定要正确否则会调用错误
var app = getApp();
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: null,
    language: "",
    invalid: 0,
    expect: 0,
    unliquidated: 0,
    liquidated: 0,
    not_yet_withdrawed: 0,
    withdrawed: 0,
    manage: 0,
    is_manage: "",
    count: 0,
    distrbution_name: "",
    distrbution_tiem: "",
    second_level: 0,
    third_level: 0,
    userName: "",
    vipId: "",
    userAvatar: "",
    mailLanguage: "",
    ecIncome: {
      lazyLoad: true, // 延迟加载
    },
    ecFans: {
      lazyLoad: true, // 延迟加载
    },
    plugin_data: null,
    //分销比例
    first_level: 0,
    //我的粉丝
    count: 0,
    //搜索key
    searchKey: "",
    order_status: null,
    Commission_status: null,
    option1: [{
        text: "请选择",
        value: 0
      },
      {
        text: "待付款",
        value: 1
      },
      {
        text: "待发货",
        value: 2
      },
      {
        text: "待收货",
        value: 3
      },
      {
        text: "已完成",
        value: 4
      },
      {
        text: "已关闭",
        value: 5
      },
    ],
    option2: [
      {
        text: "请选择",
        value: 0
      },
      {
        text: "预计佣金",
        value: 1
      },
      {
        text: "未结算",
        value: 2
      },
      {
        text: "已结算",
        value: 3
      },
      {
        text: "未提现",
        value: 4
      },
      {
        text: "已提现",
        value: 5
      },
      {
        text: "无效",
        value: 6
      },
    ],
    show: false,
    openStop: false,
    boxShow:false,
    agent_level:[],
    diyname:[],
    isnew:null,
    imgPath: app.globalData.imgPath,
    isshow:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    try {
      // 推广中心是否开启该功能，没开启跳转到指定路径
      let mailLanguage = JSON.parse(wx.getStorageSync("mailLanguage"));
      let language = wx.getStorageSync("langIndex");
      this.setData({
        language: language.en,
        mailLanguage: mailLanguage.commission,
      });
      wx.setNavigationBarTitle({
        title: mailLanguage.commission.agent ?
          mailLanguage.commission.agent : "分销商",
      });
      let basic_info = wx.getStorageSync("yz_basic_info");
      let stop_info = basic_info.popularize_page.mini.vue_route;
      for (let i = 0; i < stop_info.length; i++) {
        if (stop_info[i] == "distribution") {
          console.log(basic_info.popularize_page.mini.mini_url + "跳转的路径");
          wx.showToast({
            title: "未开启推广权限",
            duration: 1000,
            icon: "none",
            success: function () {
              setTimeout(() => {
                wx.redirectTo({
                  url: basic_info.popularize_page.mini.mini_url,
                });
              }, 1000);
            },
          });
          return;
        }
      }
    } catch (e) {
      console.log(e);
    }
    if(options.isnew == 1){
      this.setData({
        isnew:'Newdistribution'
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });
    let basicColor = wx.getStorageSync('yz_basic_info').theme_color;
    this.setData({
      basicColor:basicColor
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this._inidata();
    // this._setUserInfo(); //设置用户信息
    this.getData();
    this.getcommissionOrders();
    
  },
  changeStatus(e) {
    console.log(e, "dddddd");
    let detail = e.detail;
    this.setData({
      order_status: detail,
    });
  },
  btnSearch() {
    this.data.Commission_record = [];
    this.getcommissionOrders();
  },
  changeStatus2(e) {
    let detail = e.detail;
    this.setData({
      Commission_status: detail,
    });
  },
  tabChange(e) {
    let type, data_type;
    type = e.currentTarget.dataset.type;
    if (type === "fans_type") {
      data_type = e.detail.index;
      this.setData({
        fans_type: data_type,
      });
      this.getFans(data_type);
    } else if (type === "recordType") {
      let index = e.detail.index;
      this.setData({
        recordType: index,
        Commission_record: [],
        extension_order: [],
      });
      if (index == 0) {
        //佣金记录
        this.getcommissionOrders();
      } else if (index == 1) {
        //推广粉丝
        this.getFansRecord(index);
      }
    }
  },
  // checkCommission_status(status) {
  //   if (status == "0") return status + 1;
  //   if (!status) return "";
  //   return status + 1;
  // },
  // checkOrder_status(status) {
  //   if (status == 2) {
  //     return 1;
  //   } else if (status == 1) {
  //     return 2;
  //   } else if (status == 4) {
  //     return "-1";
  //   } else if (status == "0") {
  //     return 0;
  //   } else {
  //     return status;
  //   }
  // },
  getcommissionOrders() {
    let json = {
      search: this.data.searchKey,
      commission_type: this.data.Commission_status,
      order_status: this.data.order_status,
    };
    let urlStr = 'plugin.commission.api.new-commission.get-commission-orders';
    if(this.data.isnew == 'Newdistribution'){
      urlStr = 'plugin.suggest.api.new-commission.get-commission-orders'
    }
    app._getNetWork({
      url: app.getNetAddresss(urlStr),
      data: json,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            Commission_record: res.data.orders,
            Commission_record_set: res.data.set,
            isLoadMore: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  getFansRecord(data_type) {
    this.data.isLoadMore = false;
    let urlStr = app.getNetAddresss("finance.income-page.extension");
    app._getNetWork({
      url: urlStr,
      data: {
        extension_type: data_type,
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            extension_order: res.data,
            isLoadMore: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  toWithrawal() {
    wx.navigateTo({
      url: "/packageA/member/withdrawal/withdrawal",
    });
  },
  toastMethod(e) {
    let msg = "";
    let type = e.currentTarget.dataset.type;
    if (type == 0) {
      // 直推客户数量，点击跳转到我的客户列表；
      this.gomyRelationship();
      return;
    } else if (type == 1) {
      msg = "直推客户购买的订单总额";
    } else if (type == 2) {
      msg = `累计分销${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }=预计${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }+未结算${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }+已结算${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }，不含无效${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }，因预计${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }可能会变成无效${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }，故累计${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }数据会有所变化`;
    } else if (type == 3) {
      msg = `客户下单后根据设置计算的推广者预计获得的${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }，并非实际获得${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }，如订单退款关闭则变更为无效${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }。`;
    } else if (type == 4) {
      msg = `客户订单完成后，获得未结算${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }，满足结算期即可变更为结算${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }`;
    } else if (type == 5) {
      msg = `客户订单完成并满足结算期后推广者实际获得的${
        this.data.mailLanguage.commission ? mailLanguage.commission : "佣金"
      }。`;
    }
    wx.showModal({
      title: msg,
      showCancel: false,
    });
  },
  getFans(data_type) {
    let urlStr = app.getNetAddresss("finance.income-page.fans-charts");
    app._getNetWork({
      url: urlStr,
      data: {
        charts_type: data_type,
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            fans_fission: res.data,
          });
          if (data_type == 1) {
            this.initOrderEcharts();
          } else {
            this.initFansEcharts();
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  initOrderEcharts() {
    let echartsComponnet = this.selectComponent("#echats-fans-line");
    let maxMoney = Math.max(...this.data.fans_fission.orderCountSeries) || 50;
    let maxCount = Math.max(...this.data.fans_fission.orderPriceSeries) || 50;
    let intervalMoney = maxMoney / 5 || 5;
    let intervalCount = maxCount / 5 || 5;
    let option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          crossStyle: {
            color: "#999",
          },
        },
      },
      toolbox: {
        feature: {
          magicType: {
            show: true,
            type: ["line", "bar"],
          },
          saveAsImage: {
            show: true,
          },
        },
      },
      legend: {
        data: ["订单金额", "订单数量"],
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: this.data.fans_fission.x_axis,
        axisPointer: {
          type: "shadow",
        },
      },
      yAxis: [{
          type: "value",
          name: "订单金额",
          min: 0,
          max: maxCount,
          interval: intervalCount,
        },
        {
          type: "value",
          name: "订单数量",
          min: 0,
          max: maxMoney,
          interval: intervalMoney,
        },
      ],
      series: [{
          name: "订单金额",
          type: "bar",
          color: "#f19c70",
          data: this.data.fans_fission.orderPriceSeries,
        },
        {
          name: "订单数量",
          type: "line",
          yAxisIndex: 1,
          color: "#77c399",
          data: this.data.fans_fission.orderCountSeries,
        },
      ],
    };

    echartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      const Chart = echarts.init(canvas, null, {
        width: width,
        height: height,
      });
      Chart.setOption(option);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return Chart;
    });
  },
  initFansEcharts() {
    let echartsComponnet = this.selectComponent("#echats-fans");
    console.log(echartsComponnet);
    let maxMoney = Math.max(...this.data.fans_fission.totalFansSeries) || 50;
    let maxCount = Math.max(...this.data.fans_fission.fansNewSeries) || 50;
    let intervalMoney = maxMoney / 5 || 5;
    let intervalCount = maxCount / 5 || 5;
    let option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          crossStyle: {
            color: "#999",
          },
        },
      },
      toolbox: {
        feature: {
          saveAsImage: {},
        },
      },
      legend: {
        data: ["粉丝总数", "单日新增粉丝"],
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: this.data.fans_fission.x_axis,
        axisPointer: {
          type: "shadow",
        },
      },
      yAxis: [{
          type: "value",
          name: "总数",
          min: 0,
          max: maxMoney,
          interval: intervalMoney,
        },
        {
          type: "value",
          name: "单日",
          min: 0,
          max: maxCount,
          interval: intervalCount,
        },
      ],
      series: [{
          name: "粉丝总数",
          type: "line",
          color: "#77c399",
          data: this.data.fans_fission.totalFansSeries,
        },
        {
          name: "单日新增粉丝",
          type: "line",
          yAxisIndex: 1,
          color: "#f19c70",
          data: this.data.fans_fission.fansNewSeries,
        },
      ],
    };

    echartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      const Chart = echarts.init(canvas, null, {
        width: width,
        height: height,
      });
      Chart.setOption(option);
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return Chart;
    });
    // setTimeout(()=> {
    // 	echartsComponnet.canvasToTempFilePath({
    // 		success: res => {
    // 			this.setData({
    // 				showChats: false,
    // 				showImg: res.tempFilePath
    // 			})
    // 		},
    // 		fail: res => console.log('失败', res)
    // 	});
    // },1500)
  },
  toggle(e) {
    console.log(e)
    let id = e.currentTarget.dataset.id;
    if (this.data.display == id) {
      this.setData({
        display: ""
      })
      return;
    }
    this.setData({
      display: id
    })
  },
  pluginGoto(e) {
    // 插件跳转
    let item = e.currentTarget.dataset.item;
    let url = item.url;

    if (item.name == "courier") {
      wx.setStorage({
        key: "couriername",
        data: item.title,
      });
      wx.navigateTo({
        url: "/packageA/member/" + url + "/" + url,
      });
    } else if (item.url == "HotelManage") {
      wx.navigateTo({
        url: "/packageA/hotel/HotelManage/HotelManage?title=" + encodeURIComponent("酒店管理"),
      });
    } else if (item.url == "cloudIndex") {
      wx.navigateTo({
        url: "/packageE/others/cloudwarehouse/cloud_index/cloud_index",
      });
    } else if (item.url == "collageIndex") {
      wx.navigateTo({
        url: "/packageE/member/collage/collageIndex/collageIndex",
      });
    } else if (item.name == "m-erweima") {
      // 海报
      this.openQrCode(this.data.dataIs);
    } else if (item.mini_url) {
      wx.navigateTo({
        url: item.mini_url,
      });
    }
  },
  openQrCode(e) {
    this.setData({
      isshow: true,
    });
  },
  closeCallblack(e){
    this.setData({
      isshow:e.detail.isshow
    })
  },
  touchstart1() {

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getMoreData();
  },
  getMoreData() {
    let urlStr = "";
    let json = {};
    console.log(this.data.recordType,'dddddddddd')
    if (!this.data.isLoadMore) {
      return;
    }
    if (this.data.recordType == 1) {
      if (
        this.data.extension_order.current_page >=
        this.data.extension_order.last_page
      ) {
        this.data.isLoadMore = false;
        return;
      }
      urlStr = "finance.income-page.extension";

      this.data.extension_order.current_page += 1;
      json = {
        page: this.data.extension_order.current_page,
        extension_type: this.data.recordType,
      };
      wx.showLoading({
        title: '加载中',
      })
    } else {
      console.log(this.data.Commission_record,'wwwwwwwww')
      if (
        this.data.Commission_record.current_page >=
        this.data.Commission_record.last_page
      ) {
        this.data.isLoadMore = false;
        return;
      }
      this.data.Commission_record.current_page += 1;
      json = {
        search: this.data.searchKey,
        commission_type: this.data.Commission_status,
        order_status: this.data.order_status,
        page: this.data.Commission_record.current_page
      };
      urlStr = 'plugin.commission.api.new-commission.get-commission-orders';
      if(this.data.isnew == 'Newdistribution'){
        urlStr = 'plugin.suggest.api.new-commission.get-commission-orders'
      }
      wx.showLoading({
        title: '加载中',
      })
    }
    console.log('ddddddddddd2132')
    this.data.isLoadMore = false;
    app._getNetWork({
      url: app.getNetAddresss(urlStr),
      data: json,
      success: (resdata) => {
        wx.hideLoading({
          success: (res) => {},
        })
        this.data.isLoadMore = true;
        var res = resdata.data;
        if (res.result == 1) {
          if (this.data.recordType == 1) {
            let nextPageData = res.data.data;
            this.setData({
              "extension_order.data": this.data.extension_order.data.concat(
                nextPageData
              ),
            });
          } else {
            let nextPageData = res.data.orders.data;
            this.setData({
              "Commission_record.data": this.data.Commission_record.data.concat(
                nextPageData
              ),
            });
          }
        }
      },
      fail: function (res) {
        wx.hideLoading({
          success: (res) => {},
        })
      },
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  // //获取分销佣金
  // _getDistributionCommissionData() {
  //   let that = this;
  //   let urlStr = app.getNetAddresss(
  //     "plugin.commission.api.commission.get-commission"
  //   );
  //   app._getNetWork({
  //     url: urlStr,
  //     success: function (resdata) {
  //       var res = resdata.data;
  //       if (res.result == 1) {
  //         that.setDistributionCommissionData(res.data);
  //         that.setData({
  //           invalid: res.data.invalid,
  //         });
  //       }
  //     },
  //     fail: function (res) {
  //       console.log(res);
  //     },
  //   });
  // },
  // //设置分销佣金
  // setDistributionCommissionData(data) {
  //   this.setData({
  //     expect: data.expect,
  //     unliquidated: data.unliquidated,
  //     liquidated: data.liquidated,
  //     not_yet_withdrawed: data.not_yet_withdrawed,
  //     withdrawed: data.withdrawed,
  //     manage: data.manage,
  //   });
  //   this.data.is_manage = data.is_manage == "1" ? true : false;
  // },
  //获取我的下线总数
  _getAgentCountData() {
    let that = this;
    let urlStr = app.getNetAddresss("member.member.getMyAgentCount");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setAgentCountData(res.data);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //设置我的下线总数
  setAgentCountData(data) {
    this.setData({
      count: data.count,
    });
  },
  // //获取数据
  // _getLevelData() {
  //   let that = this;
  //   let urlStr = app.getNetAddresss(
  //     "plugin.commission.api.commission.get-agent-level"
  //   );
  //   app._getNetWork({
  //     url: urlStr,
  //     success: function (resdata) {
  //       var res = resdata.data;
  //       if (res.result == 1) {
  //         that.setDistributionInfo(res.data);
  //         that.setDistributionScaleInfo(res.data);
  //       }
  //     },
  //     fail: function (res) {
  //       console.log(res);
  //     },
  //   });
  // },
  //设置分销商 基本信息
  setDistributionInfo(data) {
    this.setData({
      distrbution_name: data.name,
      distrbution_tiem: data.created_at,
    });
  },
  //设置分销比例信息
  setDistributionScaleInfo(data) {
    this.setData({
      first_level: data.first_level,
      second_level: data.second_level,
      third_level: data.third_level,
    });
  },
  //设置用户信息
  getData() {
    let urlStr = 'plugin.commission.api.new-commission.get-commission';
    if(this.data.isnew == 'Newdistribution'){
      urlStr = 'plugin.suggest.api.new-commission.get-commission'
    }
    app._getNetWork({
      url: app.getNetAddresss(urlStr),
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res.data);
          if (!res.data.member.yz_member.is_agent) {
            wx.showModal({
              title: "提示",
              content: "请先申请成为推广员",
              success(resD) {
                if (resD.confirm) {
                  wx.redirectTo({
                    url: "/packageA/member/extension/ExtensionApply/ExtensionApply",
                  });
                } else if (resD.cancel) {
                  wx.navigateBack({
                    delta: 1,
                  });
                }
              },
            });
            return;
          }
          if(this.data.isnew == "Newdistribution"){
            this.data.diyname = res.data.diy_name;
            this.resetInitMailLanguage();
          }
          wx.setNavigationBarColor({
            frontColor: "#ffffff",
            backgroundColor: this.data.themeBaseColor,
            animation: {
              duration: 400,
              timingFunc: "easeIn",
            },
          });
          console.log(res.data,'ddddddddddd')
          this.setData({
            boxShow:true,
            agent_level:res.data.agent_level,
            userName: res.data.member.nickname,
            vipId: res.data.member.uid,
            userAvatar: res.data.member.avatar,
            commissionArr: res.data.commission,
            plugin_data: res.data.plugin_data,
            count: res.data.commission.customer,
            first_level: Number(res.data.agent_level.first_level),
          });
          this.tabChange({
            currentTarget: {
              dataset: {
                type: "fans_type",
              },
            },
            detail: {
              index: "",
            },
          });
        }else{
          if(res.msg == "该会员不是推广员"){
            wx.showModal({
              title: "提示",
              content: "请先申请成为推广员",
              success(resD) {
                if (resD.confirm) {
                  wx.redirectTo({
                    url: "/packageA/member/extension/ExtensionApply/ExtensionApply",
                  });
                } else if (resD.cancel) {
                  wx.navigateBack({
                    delta: 1,
                  });
                }
              },
            });
            return;
          }else{
            app.tips(res.msg)
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  resetInitMailLanguage(){
    this.setData({
      mailLanguage : this.data.diyname,
    })
    wx.setNavigationBarTitle({
      title: this.data.diyname.agent ? this.data.diyname.agent : "分销商",
    })
  },
  gomyRelationship() {
    wx.navigateTo({
      url: "/packageD/member/myRelationship/myRelationship",
    });
  },
  msg() {
    wx.showToast({
      icon: "none",
      title: "因商品、供应商可以独立设置佣金，您最终获得的佣金可能与此比例不同",
      duration: 3000,
    });
  },
  openDrop(e) {
    this.setData({
      openStop: true,
    });
  },
  closeDrop() {
    this.setData({
      openStop: false,
    });
  },
  onClose() {
    this.setData({
      show: false,
    });
  },
  showTap() {
    this.setData({
      show: true,
    });
  },
  gocommission() {
    wx.navigateTo({
      url: "/mircoApp/commission/commission/commission",
    });
  },
  gounsettled() {
    wx.navigateTo({
      url: "/mircoApp/commission/unsettled/index",
    });
  },
  goalreadySettled() {
    wx.navigateTo({
      url: "/mircoApp/commission/alreadySettled/index",
    });
  },
  gonotPresent() {
    wx.navigateTo({
      url: "/mircoApp/commission/notPresent/index",
    });
  },
  gopresent() {
    wx.navigateTo({
      url: "/mircoApp/commission/present/index?type=0",
    });
  },
  goinvalid() {
    wx.navigateTo({
      url: "/mircoApp/commission/present/index?type=1",
    });
  },
  godistributionOrder(e) {
    let idx = e.currentTarget.dataset.idx;
    wx.navigateTo({
      url: "/mircoApp/commission/distributionOrder/index?selected=" +
        idx,
    });
  },
});